const app = getApp();
const api = require('../config/api');
const util = require('../utils/util');

//预览图片
const onPreviewPics = function (e) {
  var src = e.currentTarget.dataset.src;
  var list = e.currentTarget.dataset.list;
  wx.previewImage({
    current: src,
    urls: list,
  })
}

//获取推荐标签
const getShopBanner = function () {
  let that = this;
  util.request(api.getShopBannerUrl).then(function (res) {
    let args = {};
    args.banner = res.data
    that.setData(args)
  })
}

const getShopNotice = function () {
  let that = this;
  util.request(api.getShopNoticeUrl).then(function (res) {
    let args = {};
    args.notice = res.data
    that.setData(args)
  })
}

const getShopClassify = function () {
  let that = this;
  util.request(api.getShopClassifyUrl).then(function (res) {
    let args = {};
    args.cats = that.data.cats.concat(res.data);
    that.setData(args)
  })
}

const getShopIndexRecommend = function () {
  let that = this;
  util.request(api.getShopIndexRecommendUrl, {
    page: that.data.page
  }).then(function (res) {
    let data = res.data;
    let args = {};
    if (data.data.length > 0) {
      args.recommendList = data.data;
    } else if (data.data == "") {
      args.isLastPage = true;
    }
    args.page = data.current_page;
    that.setData(args);
    if (data.data.length > 0) {
      if (that.data.page == 1) {
        wx.lin.renderWaterFlow(that.data.recommendList, true);
      } else {
        wx.lin.renderWaterFlow(that.data.recommendList, false);
      }
    }
  })
}

const getShopGoodsDetails = function () {
  let that = this;
  util.request(api.getShopGoodsDetailsUrl, {
    id: that.data.id
  }).then(function (res) {
    let serviceTxt = '';
    for (var v of res.data.service) {
      serviceTxt += v.name + '、';
    }
    serviceTxt = serviceTxt.slice(0, serviceTxt.length - 1)
    let args = {};
    args.serviceTxt = serviceTxt;
    args.goodsinfo = res.data;
    args.param = res.data.param_data;
    that.setData(args)
  })
}

const getShopInspiration = function () {
  let that = this;
  util.request(api.getShopInspirationUrl).then(function (res) {
    let args = {};
    args.swiperList = res.data;
    that.setData(args)
    that.towerSwiper('swiperList');
  })
}

const getShopHotList = function () {
  let that = this;
  util.request(api.getShopHotListUrl).then(function (res) {
    let args = {};
    args.hotList = res.data;
    that.setData(args)
  })
}

const getShopPlate = function () {
  let that = this;
  util.request(api.getShopPlateUrl).then(function (res) {
    let args = {};
    args.plateList = res.data;
    args.topload = false;
    that.setData(args)
  })
}

const getShopClassifyGoodsList = function () {
  let that = this;
  util.request(api.getShopClassifyGoodsListUrl, {
    cid: that.data.curIdx,
    page: that.data.page,
  }).then(function (res) {
    let data = res.data;
    let args = {};
    args.loading = false;
    if (data.data.length > 0) {
      args.goodsList = that.data.goodsList.concat(data.data);
    } else if (data.data == "") {
      args.isLastPage = true;
      if (data.current_page == 1) {
        args.isEmpty = true;
      }
    }
    args.page = data.current_page;
    that.setData(args);
  })
}

const getShopGoodsSearch = function () {
  let that = this;
  util.request(api.getShopGoodsSearchUrl, {
    keyword: that.data.keyword,
    page: that.data.page,
  }).then(function (res) {
    let data = res.data;
    let args = {};
    args.loading = false;
    if (data.data.length > 0) {
      args.goodsList = that.data.goodsList.concat(data.data);
    } else if (data.data == "") {
      args.isLastPage = true;
      if (data.current_page == 1) {
        args.isEmpty = true;
      }
    }
    args.page = data.current_page;
    that.setData(args);
  })
}

const getShopGoodsPosts = function () {
  let that = this;
  util.request(api.getShopGoodsPostsUrl, {
    gid: that.data.id
  }).then(function (res) {
    let args = {};
    args.goodsComment = res.data;
    that.setData(args)
  })
}

const getShopAddCart = function () {
  let that = this;
  let paraminfo = that.data.paraminfo;
  util.request(api.getShopAddCartUrl, {
    gid: that.data.id,
    pid: paraminfo.id,
    pname: that.data.goodsinfo.name,
    pvalue: paraminfo.value,
    pic: paraminfo.pic,
    price: paraminfo.price,
    vip_price: paraminfo.vip_price,
    stock: paraminfo.stock,
    num: that.data.num,
  }, "POST").then(function (res) {
    if (res.code == 200) {
      that.setData({
        detailsShow: false
      })
      wx.showToast({
        title: that.data.num + ' 件商品已加入购物袋！',
        icon: 'none',
        duration: 2000
      })
      that.userCartCount();
    } else {
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }
  })
}

const getShopUserCartList = function () {
  let that = this;
  util.request(api.getShopUserCartListUrl).then(function (res) {
    let args = {};
    if (res.data.length > 0) {
      args.cartGoods = res.data;
    } else {
      args.isEmpty = true;
    }
    that.setData(args)
    that.calculateFun();
  })
}

const getShopSaveCartNum = function (pid, num, idx, value) {
  let that = this;
  util.request(api.getShopSaveCartNumUrl, {
    pid: pid,
    num: num,
  }).then(function (res) {
    if (res.code == 200) {
      let cartGoods = that.data.cartGoods;
      cartGoods[idx].num = num;
      let args = {};
      args.cartGoods = cartGoods;
      args.numindx = value;
      that.setData(args);
      that.calculateFun();
    } else {
      wx.showToast({
        title: '库存不够啦，该商品最多可追加' + res.data + '件',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

const getShopCheckCartGoods = function (pid, check) {
  let that = this;
  util.request(api.getShopCheckCartGoodsUrl, {
    pid: pid,
    check: check,
  }).then(function (res) {
    that.calculateFun();
  })
}

const getShopAllCheckCartGoods = function (is_check) {
  let that = this;
  util.request(api.getShopAllCheckCartGoodsUrl, {
    is_check: is_check,
  }).then(function (res) {
    that.getShopUserCartList();
  })
}

const getShopDelCartGoods = function () {
  let that = this;
  util.request(api.getShopDelCartGoodsUrl, {
    cid: that.data.cid,
  }).then(function (res) {
    if (that.data.cartGoods.length > 0) {
      that.calculateFun();
    } else {
      that.setData({
        isEmpty: true
      })
    }
  })
}

const getShopGetAddsList = function () {
  let that = this;
  util.request(api.getShopGetAddsListUrl).then(function (res) {
    let args = {};
    args.list = res.data;
    that.setData(args);
  })
}

const getShopSaveAdds = function () {
  let that = this;
  let is_check = 0;
  if (that.data.is_check) {
    is_check = 1;
  }
  util.request(api.getShopSaveAddsUrl, {
    aid: that.data.aid,
    name: that.data.name,
    mobile: that.data.mobile,
    province: that.data.address[0],
    city: that.data.address[1],
    county: that.data.address[2],
    adds: that.data.adds,
    is_check: is_check,
  }, 'POST').then(function (res) {
    wx.showToast({
      title: '保存成功',
      icon: 'none',
    })
    that.setData({
      addsPopup: false
    })
    that.getShopGetAddsList();
  })
}

const getShopDelAdds = function () {
  let that = this;
  util.request(api.getShopDelAddsUrl, {
    aid: that.data.aid
  }).then(function (res) {})
}

const getShopGetCheckAdds = function () {
  let that = this;
  util.request(api.getShopGetCheckAddsUrl, {
    aid: that.data.aid
  }).then(function (res) {
    let args = {};
    args.aid = res.data.id;
    args.addsinfo = res.data;
    that.setData(args);
  })
}

const getShopPliceOrderGoods = function () {
  let that = this;
  util.request(api.getShopPliceOrderGoodsUrl).then(function (res) {
    let args = {};
    args.goodslist = res.data;
    that.setData(args);
    that.calculateFun();
  })
}

const shopPliceOrder = function () {
  let that = this;
  util.request(api.shopPliceOrderUrl, {
    aid: that.data.aid,
    user_remark: that.data.user_remark,
    goods_amount: that.data.amount,
    discounts_amount: that.data.discountsAmount,
    order_amount: that.data.vipAmount,
    order_goods: that.data.goodslist,
  }, "POST").then(function (res) {
    wx.hideLoading();
    if (res.code == 200) {
      let payParam = res.data;
      wx.requestPayment({
        'timeStamp': payParam.timeStamp,
        'nonceStr': payParam.nonceStr,
        'package': payParam.package,
        'signType': payParam.signType,
        'paySign': payParam.paySign,
        'success': function (res) {
          that.setData({
            payPopup: true,
            payTitle: '支付成功'
          })
        },
        'fail': function (res) {
          that.setData({
            payPopup: true,
            payTitle: '支付失败'
          })
        }
      });
    }
  })
}

const getShopOrderList = function () {
  let that = this;
  util.request(api.getShopOrderListUrl, {
    page: that.data.page,
    type: that.data.baridx,
  }).then(function (res) {
    let data = res.data;
    let args = {};
    args.loading = false;
    if (data.data.length > 0) {
      args.list = that.data.list.concat(data.data);
    } else if (data.data == "") {
      args.isLastPage = true;
      if (data.current_page == 1) {
        args.isEmpty = true;
      }
    }
    args.page = data.current_page;
    that.setData(args);
  })
}

const getShopDelOrder = function () {
  let that = this;
  util.request(api.getShopDelOrderUrl, {
    oid: that.data.oid
  }).then(function (res) {})
}

const getShopCancelOrder = function () {
  let that = this;
  util.request(api.getShopCancelOrderUrl, {
    oid: that.data.oid
  }).then(function (res) {})
}

const shopPayment = function (e) {
  let that = this;
  wx.showLoading({
    title: '正在唤起支付',
  })
  let orderSn = e.currentTarget.dataset.on;
  let order_amount = e.currentTarget.dataset.amount;
  util.request(api.shopPaymentUrl, {
    orderSn: orderSn,
    order_amount: order_amount,
  }, "POST").then(function (res) {
    wx.hideLoading();
    if (res.code == 200) {
      let payParam = res.data;
      wx.requestPayment({
        'timeStamp': payParam.timeStamp,
        'nonceStr': payParam.nonceStr,
        'package': payParam.package,
        'signType': payParam.signType,
        'paySign': payParam.paySign,
        'success': function (res) {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            'success': function (res) {
              that.setData({
                baridx: 2,
                list: [],
                page: 1,
                loading: false,
                loadmoreShow: false,
                isLastPage: false,
                isEmpty: false,
                particulars: false,
              })
              that.getShopOrderList();
            }
          })
        },
        'fail': function (res) {
          wx.showToast({
            title: '取消支付',
            icon: 'error'
          })
        }
      });
    } else {
      wx.showToast({
        title: '唤起支付失败',
        icon: 'error'
      })
    }
  })
}

const getShopPushDelivery = function () {
  let that = this;
  util.request(api.getShopPushDeliveryUrl, {
    on: that.data.on,
    title: '催发货',
    message: '订单：' + that.data.on + '用户在催发货了。',
  }, 'POST').then(function (res) {
    if (res.code == 200) {
      wx.showToast({
        title: '订单催发货通知成功，我们会尽快为您处理。',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }
  })
}

const getShopOrderRefund = function () {
  let that = this;
  let refundGoods = that.data.refundGoods;
  let message = '订单：' + that.data.on + '；' + refundGoods.quantity + '件 ' + refundGoods.name + '【' + refundGoods.product + '】' + '会员价为：【' + refundGoods.vip_price + '】普通价为：' + refundGoods.price + ' 申请退款。';
  util.request(api.getShopOrderRefundUrl, {
    opid: refundGoods.product_id,
    oid: refundGoods.order_id,
    on: that.data.on,
    title: '退款申请',
    message: message,
  }, 'POST').then(function (res) {
    wx.showToast({
      title: '退款申请提交成功，我们会尽快为您处理。',
      icon: 'none',
      duration: 2000
    })
  })
}

const getShopConfirmReceipt = function () {
  let that = this;
  util.request(api.getShopConfirmReceiptUrl, {
    oid: that.data.oid
  }).then(function (res) {
    that.setData({
      baridx: 4,
      list: [],
      page: 1,
      loading: false,
      loadmoreShow: false,
      isLastPage: false,
      isEmpty: false,
      particulars: false,
    })
    that.getShopOrderList();
  })
}

const getShopOrderCount = function () {
  let that = this;
  util.request(api.getShopOrderCountUrl).then(function (res) {
    let tapbar = that.data.tapbar;
    tapbar[1].count = res.data.payCount;
    tapbar[2].count = res.data.deliverCount;
    tapbar[3].count = res.data.closedCount;
    that.setData({
      tapbar: tapbar
    })
  })
}

const getShopRefundGoods = function () {
  let that = this;
  let refundGoods = that.data.refundGoods;
  let message = '订单：' + that.data.on + '；' + refundGoods.quantity + '件 ' + refundGoods.name + '【' + refundGoods.product + '】' + '会员价为：【' + refundGoods.vip_price + '】普通价为：' + refundGoods.price + ' 申请退货退款。';
  util.request(api.getShopRefundGoodsUrl, {
    opid: refundGoods.product_id,
    oid: refundGoods.order_id,
    on: that.data.on,
    title: '退货退款申请',
    message: message,
  }, 'POST').then(function (res) {
    wx.setClipboardData({
      data: that.data.on,
    })
    that.setData({
      serviceShow: true
    })
  })
}

const userCartCount = function () {
  let that = this;
  util.request(api.userCartCountUrl).then(function (res) {
    that.setData({
      cartCount: res.data
    })
  })
}


module.exports = function (obj) {


  obj.userCartCount = userCartCount;
  obj.getShopRefundGoods = getShopRefundGoods;
  obj.getShopOrderCount = getShopOrderCount;
  obj.getShopConfirmReceipt = getShopConfirmReceipt;
  obj.getShopOrderRefund = getShopOrderRefund;
  obj.getShopPushDelivery = getShopPushDelivery;
  obj.shopPayment = shopPayment;
  obj.getShopCancelOrder = getShopCancelOrder;
  obj.getShopDelOrder = getShopDelOrder;
  obj.getShopOrderList = getShopOrderList;
  obj.shopPliceOrder = shopPliceOrder;
  obj.getShopPliceOrderGoods = getShopPliceOrderGoods;
  obj.getShopDelAdds = getShopDelAdds;
  obj.getShopSaveAdds = getShopSaveAdds;
  obj.getShopGetAddsList = getShopGetAddsList;
  obj.getShopGetCheckAdds = getShopGetCheckAdds;
  obj.getShopDelCartGoods = getShopDelCartGoods;
  obj.getShopAllCheckCartGoods = getShopAllCheckCartGoods;
  obj.getShopCheckCartGoods = getShopCheckCartGoods;
  obj.getShopSaveCartNum = getShopSaveCartNum;
  obj.getShopUserCartList = getShopUserCartList;
  obj.getShopAddCart = getShopAddCart;
  obj.getShopGoodsPosts = getShopGoodsPosts;
  obj.onPreviewPics = onPreviewPics;
  obj.getShopBanner = getShopBanner;
  obj.getShopNotice = getShopNotice;
  obj.getShopClassify = getShopClassify;
  obj.getShopIndexRecommend = getShopIndexRecommend;
  obj.getShopGoodsDetails = getShopGoodsDetails;
  obj.getShopInspiration = getShopInspiration;
  obj.getShopHotList = getShopHotList;
  obj.getShopPlate = getShopPlate;
  obj.getShopClassifyGoodsList = getShopClassifyGoodsList;
  obj.getShopGoodsSearch = getShopGoodsSearch;
}